//
//  MYActivityDetailViewController.m
//  app001
//
//  Created by xionghao on 15/10/9.
//  Copyright © 2015年 xionghao. All rights reserved.
//

#import "MYActivityDetailViewController.h"
#import "ZtEidtBar.h"
#import "ShareView.h"
#import "ZTListContent.h"
#import "Puser.h"
#import "UserInfoUpdateResde.h"
#import "PostActivityTableViewController.h"
#import "GMDCircleLoader.h"
#import "ZTActivityPostSUSViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "MyZTCarDetailTableViewController.h"


@interface MYActivityDetailViewController ()<EidtBarDelegate,ShareclickDelegate>
@property (nonatomic,strong) UIScrollView *scrollview;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) ZtEidtBar *toolbar;
@property (nonatomic,strong) UIWebView *webview;

@end

@implementation MYActivityDetailViewController

-(void)shareclickWithIndex:(NSInteger)index{
    
}
-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self removeSUS];
    self.navigationItem.title=!self.isActiviy?@"纪念详情":@"活动详情";
    self.view.backgroundColor=bgGarycolor;
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"top-r-two"] style:UIBarButtonItemStyleDone target:self action:@selector(share)];
    self.automaticallyAdjustsScrollViewInsets=NO;
    UIWebView *webview=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, XHScreenwidth, XHScreenheight)];
    webview.backgroundColor=[UIColor clearColor];
    webview.scrollView.contentInset=UIEdgeInsetsMake(64, 0, 0, 0);
    webview.scalesPageToFit=YES;
    [self.view addSubview:webview];
    webview.opaque=NO;
    self.webview=webview;
    JSContext *context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"log"] = ^(int i) {
        NSLog(@"%d",i);
        dispatch_async(dispatch_get_main_queue(), ^{
            ZTListContent *content=self.mode.content[i];
            MyZTCarDetailTableViewController *vc=[MyZTCarDetailTableViewController Viewcontroller];
            vc.isFromSearch=YES;
            vc.ID=content.ID;
            [self.navigationController pushViewController:vc animated:YES];
        });
    
    };
    
    [self setuptoolbar];
    [self setupdata];
    // Do any additional setup after loading the view.
}
-(void)removeSUS{
    NSMutableArray *marray=[NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[ZTActivityPostSUSViewController class]]) {
            [marray removeObject:vc];
        }
    }
    self.navigationController.viewControllers=marray;
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(void)setupdata{
   
    
    if (self.mode) {
        [self loaddata];
    }else{
        GMDCircleLoader *loader=[GMDCircleLoader setOnView:self.view withTitle:@"加载中..." animated:YES];
        [loader start];
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        NSInteger power=[self.user.power integerValue];
        params[@"user_id"]=power<5?self.user.user_id:self.user.com_id;
        params[@"type"]=power<5?@"person":@"company";
        
        if (self.isActiviy) {
            params[@"action"]=@"activity";
        }else{
        params[@"action"]=@"jn";
        }
        params[@"jnid"]=self.ID;
        [PostUitls Post:mynewzturl parameters:params success:^(id response) {
            [ZTActivityModel setupReplacedKeyFromPropertyName:^NSDictionary *{
                return @{@"ID":@"id"};
            }];
            [ZTListContent setupReplacedKeyFromPropertyName:^NSDictionary *{
                return @{@"ID":@"id"};
            }];
            
            [ZTActivityModel setupObjectClassInArray:^NSDictionary *{
                return @{@"content":@"ZTListContent"};
            }];

            NSDictionary *dict=response;
            ZTActivityModel *mode=[ZTActivityModel objectWithKeyValues:dict[@"data"]];
            self.mode=mode;
            [self loaddata];
            [GMDCircleLoader  hideFromView:self.view animated:YES];
            
        } failure:^(NSError *error) {
            
        }];
    }
    
}

-(void)loaddata{
    NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"jiliandetail"
                                                          ofType:@"html"];
    NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath
                                                    encoding:NSUTF8StringEncoding
                                                       error:nil];
    
    htmlCont=[htmlCont stringByReplacingOccurrencesOfString:@"[标题]" withString:self.mode.title];
    htmlCont=[htmlCont stringByReplacingOccurrencesOfString:@"[时间]" withString: [NSDate dateStrFromTimeStr:self.mode.updatetime]];
    htmlCont=[htmlCont stringByReplacingOccurrencesOfString:@"[简介]" withString:self.mode.msg];
    
    NSString *imgcontent=@"";
    for (int i=0; i<self.mode.content.count; i++) {
        ZTListContent *content=self.mode.content[i];
        if ([content.type integerValue]==2) {
            imgcontent=[imgcontent stringByAppendingString:[NSString stringWithFormat:@"<div class=\"clickcontent\" onclick=\"log(%d)\" ><img class=\"linkbanner\" src=\"linkimg.png\"></img><img class=\"clickcontent-img\"  src=\"%@\"/></div><p class=\"imginfo\">%@</p>",i,[NSString getImageURLstr:content.pic],content.msg?content.msg:@""]];
        }else{
            imgcontent= [imgcontent stringByAppendingString:[NSString stringWithFormat:@"<img src=\"%@\"> <p class=\"imginfo\">%@</p>",[NSString getImageURLstr:content.pic],content.msg?content.msg:@""]];
        }

    }
    
    htmlCont=[htmlCont stringByReplacingOccurrencesOfString:@"[图文]" withString:imgcontent];
    
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    [self.webview loadHTMLString:htmlCont baseURL:baseURL];
}

-(void)EidtClickWithIndex:(NSInteger)index{
    if (!self.isActiviy) {
        if (!self.isFromdown) {
            [self deleteOrDown:index==0];
        }else{
            if (index==1) {
                PostActivityTableViewController *vc=[PostActivityTableViewController viewcontroller];
                vc.isActivtiy=NO;
                vc.mode=self.mode;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [self deleteOrDown:YES];
            }
        }
        
    }else{
        if (!self.isFromdown) {
            [self deleteOrDown:index==0];
        }else{
            if (index==1) {
                PostActivityTableViewController *vc=[PostActivityTableViewController viewcontroller];
                vc.isActivtiy=YES;
                vc.mode=self.mode;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [self deleteOrDown:YES];
            }
        }

    }
}


-(void)deleteOrDown:(BOOL)isdelete{
    
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.labelText=@"正在操作";
    
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    
    if (isdelete) {
        if (self.isActiviy) {
            params[@"action"]=@"del_act";
        }else{
        params[@"action"]=@"del_fabu";
        }
    }else{
        if (self.isActiviy) {
            params[@"action"]=@"can_act";
        }else{
        params[@"action"]=@"can_fabu";
       
        }
    }
    
    
    NSInteger power=[self.user.power integerValue];
    params[@"user_id"]=power<5?self.user.user_id:self.user.com_id;
    params[@"type"]=power<5?@"person":@"company";
    
    NSMutableArray *IDarray=[NSMutableArray array];
    
    [IDarray addObject:self.mode.ID];
    params[@"jnid"]=[NSString DataTOjsonString:IDarray];
    [PostUitls Post:mynewzturl parameters:params success:^(id response) {
        hud.mode = MBProgressHUDModeText;
        
        UserInfoUpdateResde *resdemode=[UserInfoUpdateResde resdeWithDict:response];
        if ([resdemode.state integerValue]==400) {
            if (!isdelete) {
                [self.toolbar updatetitle:@[@"删除",@"修改"]];
                self.isFromdown=YES;
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
        hud.labelText=resdemode.msg;
        [hud hide:YES afterDelay:0.5];
    } failure:^(NSError *error) {
        
        hud.mode = MBProgressHUDModeText;
        hud.labelText=NetWorkError;
        [hud hide:YES afterDelay:1];
    }];
    
    
}



-(void)setuptoolbar{
    if (self.isFromOtherZT) {
        return;
    }
    NSArray *array=@[@"删除",@"取消发布"];
    if (self.isFromdown) {
        array=@[@"删除",@"修改"];
    }
    ZtEidtBar *eidtbar=[[ZtEidtBar alloc]initWithBtnTitleArray:array WithDelegate:self];
    [self.view addSubview:eidtbar];
    self.toolbar=eidtbar;
}
-(void)share{
    NSArray *titlearray=@[@"微信",@"朋友圈",@"短信"];
    UIImage *weixin=[UIImage imageNamed:@"weixin"];
    UIImage *pengyou=[UIImage imageNamed:@"liulan"];
    UIImage *sms=[UIImage imageNamed:@"duanxin"];
    NSArray *icon=@[weixin,pengyou,sms];
    ShareView *share=[[ShareView alloc]initWithTitle:titlearray andIcons:icon delegate:self];
    [share show];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
